package com

import (
	"errors"
	"sort"
)

const (
	ApiErrMsgNoJson       = "need json param"
	ApiErrMsgNeedParam    = "need param"
	ApiErrMsgTokenInvalid = "token invalid or not exists"
	ApiErrMsgTokenExpired = "token expired"
	ApiErrMsgSign         = "md5 sign error"
	ApiErrMsgSystem       = "system error"
)

const (
	ApiErrTokenInvalid = 100
	ApiErrTokenExpired = 101
	ApiErrSignError    = 102
	ApiErrUnknow       = 1
)

type JsonApiRep struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func ApiSucc(data interface{}) *JsonApiRep {
	return ApiReturn(0, "succ", data)
}

func ApiUnknowFailed(msg string) *JsonApiRep {
	return ApiReturn(ApiErrUnknow, msg, nil)
}

func ApiReturn(code int, msg string, data interface{}) *JsonApiRep {
	jar := &JsonApiRep{code, msg, data}
	return jar
}

func SignParams(params map[string]string, secureKey string) (string, error) {
	if len(params) == 0 {
		return "", errors.New("SignParams empty params")
	}

	strForSign := ""
	keys := make([]string, 0, len(params))
	for k, _ := range params {
		keys = append(keys, k)
	}

	sort.Strings(keys)
	for _, k := range keys {
		strForSign = strForSign + k + params[k]
	}

	strForSign = strForSign + secureKey

	return Md5(strForSign), nil
}
